package auctionServer.businessLogic;

import auctionServer.AuctionServer;
import auctionServer.io.IOManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class ItemManager implements Runnable {

	private AuctionServer auctionServer;
	private List<Item> items;
	private int id;
	private boolean workingFlag;

	public ItemManager(AuctionServer auctionServer) {
		items = Collections.synchronizedList(new ArrayList<Item>());
		this.auctionServer = auctionServer;
		id = 0;
		workingFlag = true;
	}

	
	public void run() {
		while(workingFlag){
			Date now = new Date();
			for (Item i : items) {
				if(now.after(i.getEndDate())){
					i.auctionFinished();
					items.remove(items.indexOf(i));
					break;
				}
			}
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				IOManager.throwWarning("Sleep interupted!");
			}
		}
	}

	public void stopChecking() {
		workingFlag = false;
	}

	public void createItem(Peer peer, int duration, String description) {
		Item i = new Item(getNextId(), peer, description, new Date(new Date().getTime() + duration*1000));
		items.add(i);
		peer.sendMessage("An auction \'"+description+"\' with id "+id+" has been created and will end on "+i.getEndDate());
	}

	private int getNextId() {
		return ++id;
	}

	public String getList() {
		String list="";
		for (Item item : items) {
			list += item + System.getProperty("line.separator");
		}
		return list;
	}

	public void bid(Peer peer, int givenID, int amount) {
		boolean done = false;
		for (Item item : items) {
			if(item.getId() == givenID){
				item.bid(peer,amount);
				done = true;
				break;
			}
		}
		if(!done){
			peer.sendMessage(givenID+" id item can not found");
		}
	}

}
